//-------------------------------------------------------------------
//	Copyright (c) 2010-2011  Zhirnov Andrey
//	This file is part of the "UXGEN_ResourceConverter" project.
//	See copyright notice in "Converter.h".
//-------------------------------------------------------------------

#include <windows.h>
#include "stdafx.h"
#include "CConverter.h"
#include "..\\tests\\Test.h"


HMODULE		hModule		= NULL;
bool		bTerminate	= false;

array< CConverter *>	ConverterInstances;


extern "C" bool CALLBACK CreateConverter(IConverter *&pConverter, uint uVersion)
{
	if ( uVersion != _CONVERTER_HEADER_VERSION_ )
	{
		MessageBox(NULL, "Library version differs from header version!", "Converter", MB_OK | MB_ICONSTOP | MB_SETFOREGROUND);
		return false;
	}

	ConverterInstances.PushBack( new CConverter() );
	bTerminate = true;

	pConverter = (IConverter *)ConverterInstances.Back();
	return true;
}


extern "C" bool CALLBACK FreeConverter(IConverter *pConverter)
{
	if ( pConverter == nullptr )
		return false;

	for (uint i = 0; i < ConverterInstances.Count(); ++i)
		if ( pConverter == ConverterInstances[i] )
		{
			delete ConverterInstances[i];
			ConverterInstances.Erase( i );
			return true;
		}

	return false;
}


#ifndef _TEST

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
	switch ( ul_reason_for_call )
	{
		case DLL_PROCESS_ATTACH :
			::hModule = hModule;
			break;

		case DLL_PROCESS_DETACH :
		
			for (uint i = 0; i < ConverterInstances.Count(); ++i)
			{
				if ( ConverterInstances[i] != nullptr ) {
					delete ConverterInstances[i];
					ConverterInstances.Erase( i );
				}
			}

			ConverterInstances.Clear();

			if ( bTerminate )
				::TerminateProcess( GetCurrentProcess(), 1 );

			break;
	}

	return TRUE;
}

#else

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	IConverter	*p_conv = nullptr;

	if ( CreateConverter( p_conv, _CONVERTER_HEADER_VERSION_ ) )
	{
		RunConverterTests( p_conv );
		FreeConverter( p_conv );
		return 0;
	}

	return 1;
}

#endif	// _TEST